#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cerrno>
#include <cstring>
#include <string>
#include "Log.hpp"
#include "Comm.hpp"

const static int defaultsize = 1024;

void Usage(std::string process)
{
    std::cout << "Usage: " << process << " server_ip server_port" << std::endl;
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return Usage_Err;
    }
    // 获取服务器IP和端口
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        lg.LogMessage(Fatal, "socket errr, %d : %s\n", errno, strerror(errno));
        exit(Socket_Err);
    }
    lg.LogMessage(Info, "socket success, sockfd: %d\n", sockfd);

    // 填写server端结构体
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    while (true)
    {
        // 输入
        std::string inbuffer;
        std::cout << "Please Enter# ";
        std::getline(std::cin, inbuffer);
        // 发消息
        ssize_t n = sendto(sockfd, inbuffer.c_str(), sizeof(inbuffer), 0, (struct sockaddr *)&server, sizeof(server));
        if (n > 0) // 发送成功
        {
            char buffer[defaultsize];
            // 收消息
            struct sockaddr_in temp;
            socklen_t len = sizeof(temp);
            ssize_t m = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&temp, &len);
            if (m > 0)
            {
                buffer[m] = 0;
                std::cout << "server echo# " << buffer << std::endl;
            }
            else
                break;
        }
        else
            break;
    }
    close(sockfd);
    return 0;
}